import React, { PureComponent } from 'react'

import store from '../store'

import {
  addAction,
  incAction
} from '../store/actionCreators'

export default class home extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      // store赋值给state
      counter: store.getState().counter
    }
  }

  // 监听
  componentDidMount() {
    this.unsubscribe = store.subscribe(() => {
      this.setState({
        counter: store.getState().counter
      })
    })
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    return (
      <div>
        <h1>Home</h1>
        <h2>当前计数：{this.state.counter}</h2>
        <button onClick={() => this.increment()}>+1</button>
        <button onClick={() => this.addNumber(5)}>+5</button>
      </div>
    )
  }
  
  increment() {
    store.dispatch(incAction())
  }
  addNumber(num) {
    store.dispatch(addAction(num))
  }


}
